<template>
  <div>
    <p class="titleMess">材料信息</p>
    <a-divider />
    <a-form :model="uploadForm" :label-col="labelCol" style="margin-top: 20px">
      <a-form-item ref="mediaType" label="材料类型" name="mediaType" :required="true">
        <a-select class="choose" v-model:value="mediaType" @change="changemediaType" :options="mediaTypeData" style="width: 240px" placeholder="请选择要上传的文件类型" />
      </a-form-item>
      <!-- 链接 -->
      <div v-if="linkVisible" :key="4">
        <a-form-item label="文本" name="mediaContent" ref="mediaContent" >
          <a-textarea v-model:value="mediaContent" placeholder="填写说明，发布时的默认值" style="min-height: 180px" auto-size />
        </a-form-item>
        <a-form-item class="linkData" ref="urlTitle" name="urlTitle" label="链接标题" :required="true">
          <a-input v-model:value="urlTitle" placeholder="链接标题" />
        </a-form-item>
        <a-form-item class="linkData" ref="url" name="url" label="网页链接" :required="true">
          <a-input v-model:value="url" placeholder="网址链接http://" />
        </a-form-item>
        <a-form-item class="linkData" ref="uploadImg" name="uploadImg" label="上传封面" :required="true">
          <a-upload :file-list="fileList" :action="uploadUrl" :accept="'.jpg,.jpeg,.png'" list-type="picture-card" @change="handleChangeImg" :before-upload="beforeUploadImg" :remove="handelRemove">
            <div v-if="fileList.length < 1">
              <div class="ant-upload-text" style="margin-top: 8px">
                +上传封面
              </div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancelImg">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
          <span class="tishi">图片(image):10MB,支持JPG,PNG格式,朋友圈类型图片不超过1440 x 1080</span>
        </a-form-item>
      </div>

      <!-- 图片 -->
      <div v-if="imgVisible" :key="2">
        <a-form-item label="文本" name="mediaContent" ref="mediaContent" >
          <a-textarea v-model:value="mediaContent" placeholder="填写说明，发布时的默认值" style="min-height: 180px" auto-size />
        </a-form-item>
        <a-form-item label="图片" :required="true">
          <a-upload
            :accept="'.jpg,.jpeg,.png'"
            :file-list="fileList"
            :action="uploadUrl"
            list-type="picture-card"
            @change="handleChangeImg"
            :before-upload="beforeUploadImg"
            :remove="handelRemove"
        
          >
            <div v-if="fileList.length < 9">
              <div class="ant-upload-text" style="margin-top: 8px">
                +上传图片
              </div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancelImg">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
          <span class="tishi">最多9张图片(image):10MB,支持JPG,PNG格式,朋友圈类型图片不超过1440 x 1080</span>
        </a-form-item>
      </div>
      <!-- 视频s -->
      <div v-if="movieVisible" :key="3">
        <a-form-item label="文本" name="mediaContent" ref="mediaContent" >
          <a-textarea v-model:value="mediaContent" placeholder="填写说明，发布时的默认值" style="min-height: 180px" auto-size />
        </a-form-item>
        <a-form-item label="视频" :required="true">
          <a-upload
            :file-list="affixFileList"
            :action="uploadUrl"
            :accept="'video/mp4'"
            list-type="picture-card"
            @change="handleChangeVideo"
            :before-upload="videoBeforeUpload"
            :remove="handelRemove"
            :preview-file="handlePreviewFile"
            @preview="handlePreviewVideo"
          >
            <div v-if="affixFileList.length < 1">
              <div class="ant-upload-text" style="margin-top: 8px">
                +上传视频
              </div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancelImg">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
          <span class="tishi">视频(video):10MB,支持MP4格式,朋友圈类型视频时长不超过30秒</span>
        </a-form-item>
      </div>
      <!-- 视频e -->

      <!-- 小程序s -->
      <div v-if="programVisible" :key="5">
        <a-form-item label="文本" name="mediaContent" ref="mediaContent" >
          <a-textarea v-model:value="mediaContent" placeholder="填写说明，发布时的默认值" style="min-height: 180px" auto-size />
        </a-form-item>
        <a-form-item class="linkData" ref="urlTitle" name="urlTitle" label="小程序链接标题" :required="true">
          <a-input v-model:value="urlTitle" placeholder="链接标题" />
        </a-form-item>
        <a-form-item class="linkData" ref="url" name="url" label="小程序AppId" :required="true">
          <a-input v-model:value="url" placeholder="请输入小程序链接" />
        </a-form-item>
        <a-form-item class="linkData" label="小程序封面" :required="true">
          <a-upload :file-list="fileList" :action="uploadUrl" :accept="'.jpg,.jpeg,.png'" list-type="picture-card" @change="handleChangeImg" :before-upload="beforeUploadImg" :remove="handelRemove">
            <div v-if="fileList.length < 1">
              <div class="ant-upload-text" style="margin-top: 8px">
                +上传封面
              </div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancelImg">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>

          <span class="tishi">图片(image):10MB,支持JPG,PNG格式,朋友圈类型图片不超过1440 x 1080</span>
        </a-form-item>
      </div>
      <!-- 小程序e -->
      <!-- 文本s -->
      <div v-if="textVisible" :key="1">
        <a-form-item label="文本" name="mediaContent" ref="mediaContent" :required="true">
          <a-textarea v-model:value="mediaContent" placeholder="填写说明，发布时的默认值" style="min-height: 180px" auto-size />
        </a-form-item>
      </div>
      <!-- 文本e -->
    </a-form>
  </div>
</template>

<script>
export default {
  // props: ['mediaDetail'],
  name: 'uploadEnclosure',
  watch: {
    mediaContent(newVal, oldVal) {
      console.log(newVal)
      this.mediaContent = newVal
      this.sendDatas()
    },
    // immediate: true,
    deep: true
  },
  data() {
    return {
      labelCol: {
        style: {
          width: '120px'
        }
      },
      valKey: '',
      uploadForm: {},
      previewImage: '',
      mediaContent: '',
      url: '',
      urlTitle: '',
      urlPic: [],
      imageList: [],
      mediaType: '',
      form: [],
      uploadUrl: 'https://jic.jnby.com/activity/market-act/common/upload/multipart',
      linkVisible: false,
      imgVisible: false,
      movieVisible: false,
      programVisible: false,
      textVisible: false,
      previewVisible: false,
      mediaTypeData: [
        { label: '无', value: 0 },
        { label: '文本', value: 1 },
        { label: '图片+文本', value: 2 },
        { label: '视频+文本', value: 3 },
        { label: '链接+文本', value: 4 },
        { label: '小程序链接+文本', value: 5 }
      ],
      affixFileList: [],
      fileList: [],
      previewVideoUrl: ''
    }
  },
  created() {},

  methods: {
    handlePreviewFile(file) {
      return new Promise(resolve => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = function(e) {
          const dataUrl = e.target.result
          resolve('https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3498227956,2363956367&fm=26&gp=0.jpg')
        }
      })
    },
    handlePreviewVideo() {
      if(!this.urlPic==''){
         window.open(this.imageList[0])
      }else{
const files = this.previewVideoUrl
      window.open(files)
      }
      
    },
    setMediaData(data) {
      console.log('子组件', data)
      if (data.urlPic) {
        this.imageList = JSON.parse(data.urlPic)
      }
      // for (let mess in data) {
      //   if (data[mess] === -1) {
      //     data[mess] = '无'
      //   }
      // }
      this.mediaType = data.mediaType
      this.url = data.url
      this.mediaContent = data.mediaContent
      this.urlTitle = data.urlTitle
      this.setImage()

      this.showTypeView(this.mediaType)
    },

    handleImageData(list) {
      return list.map(item => {
        let index = this.genId(5)
        return {
          uid: index,
          name: index,
          status: 'done',
          url: item
        }
      })
    },
    genId(length) {
      return Number(
        Math.random()
          .toString()
          .substr(3, length) + Date.now()
      ).toString(36)
    },
    setImage() {
      let list = this.imageList
      console.log(list)
      this.fileList = this.handleImageData(list)
      this.affixFileList = this.handleImageData(list)
      console.log('fileList affixFileList', this.fileList)
    },
    clearData() {
      this.url = ''
      ;(this.mediaContent = ''), (this.urlTitle = ''), (this.urlPic = ''), (this.imageList = []), (this.affixFileList = []), (this.fileList = [])
    },
    isNull() {
      let key = this.mediaType
      if (key) {
        if (key === 0) {
          return
        } else if (key === 1) {
          if (this.mediaContent === '') {
            this.$message.error('请填写材料内容')
          }
        } else if (key === 2) {
          if (this.mediaContent === '' || this.urlTitle === '') {
            this.$message.error('请完善材料内容')
          }
        } else {
          if (this.mediaContent === '' || this.urlTitle === '' || this.url === '' || this.urlPic === []) {
            this.$message.error('请完善材料内容')
          }
        }
      } else {
        this.$message.error('请选择材料类型')
      }
    },
    sendDatas() {
      let uploadDatas = {
        mediaType: this.mediaType,
        url: this.url,
        mediaContent: this.mediaContent,
        urlTitle: this.urlTitle,
        urlPic: JSON.stringify(this.imageList)
      }
      if (uploadDatas.mediaType == null) {
        uploadDatas.mediaType == '1'
      }
      console.log('uploadDatas  before', uploadDatas)

      this.$emit('chooseData', uploadDatas)
    },
    // sendDatas(){
    //   this.$emit("chooseData",this.uploadDatas)
    // },
    //选择要提交的附件
    changemediaType(val) {
      console.log(val)
      this.mediaType = val

      // this.sendDatas()

      this.showTypeView(val)
      this.clearData()
      // this.valKey=val
    },
    showTypeView(val) {
      this.cleanmediaType()
      if (val === 1) {
        this.textVisible = true
      } else if (val === 2) {
        this.imgVisible = true
      } else if (val === 3) {
        this.movieVisible = true
      } else if (val === 4) {
        this.linkVisible = true
      } else if (val === 5) {
        this.programVisible = true
      }
    },
    cleanmediaType() {
      this.linkVisible = false
      this.imgVisible = false
      this.movieVisible = false
      this.programVisible = false
      this.textVisible = false
    },
    isSize(file, width, height) {
      return new Promise((resolve, reject) => {
        let _URL = window.URL || window.webkitURL
        let img = new Image()
        img.src = _URL.createObjectURL(file)
        img.onload = function() {
          console.log(img.width, img.height, 'widheoi')
          if (img.width < width && img.height < height) {
            resolve(true)
          } else {
            resolve(false)
          }
        }
      })
    },
    // 附件
    beforeUploadImg(file) {
      // this.affixFileList = []
      this.fileList = [...this.fileList, file]
      return new Promise((resolve, reject) => {
        let _this = this
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'
        const isLt5M = file.size / 1024 / 1024 < 10
        if (!isJpgOrPng) {
          _this.$message.error('只能上传png或jpg格式的图片!')
          // _this.handelRemove(file)
          return isJpgOrPng
        }
        if (!isLt5M) {
          // _this.affixFileList = []
          _this.$message.error('图片尺寸不能超过 10MB!')
          return isLt5M
        }
        _this.isSize(file, 2880, 4320).then(res => {
          console.log(res)
          if (!res) {
            // _this.affixFileList = []
            _this.$message.error('图片格式不能超过2880x4320!')
            return res
          } else {
            return resolve(true)
          }
        })
      })
    },
    getBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => resolve(reader.result)
        reader.onerror = error => reject(error)
      })
    },
    // //预览图片
    // async handlePreviewImg(file) {
    //   console.log('11111111', file)
    //   this.previewVisible = true
    //   // if (!file.url && !file.preview) {
    //   //   file.preview = await this.getBase64(file.originFileObj)
    //   // }
    //   // this.previewImage = file.url || file.preview
    //   if (file.response.data) {
    //     this.previewImage = file.response.data
    //   } 
    // },
    //上传文件改变时
    handleChangeImg(data) {
      console.log(data)
      let fileList = [...data.fileList]
      this.fileList = fileList
      console.log(this.fileList)
      if (data.file.status === 'done') {
        this.$message.success('上传成功!')
        //  console.log('handleChangeImg',data.file.response.data);
        this.imageList.push(data.file.response.data)
        console.log('affixFileList', this.affixFileList)
        console.log('imgLIst', this.imageList)
        this.sendDatas()
      }
      if (data.file.status === 'error') {
        this.$message.error('上传失败!')
      }
    },
    // 添加图片
    handleCancelImg() {
      this.previewVisible = false
    },
    // 移出图片
    handelRemove(file) {
      console.log(file)
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
      this.imageList.splice(file.uid, 1)
      // this.urlPic.forEach((item, index) => {
      //   // if (item.uid == file.uid) {
      //   //   this.urlPic.splice(index, 1);
      //   // }
      // });
      // this.fileList.splice(fileList.uid, 1)
      this.sendDatas()
    },
    //视频的上传事件
    handleChangeVideo(data) {
      this.affixFileList = []
      this.imageList = []
      console.log(data)

      let fileList = [...data.fileList]
      this.affixFileList = fileList
      if (data.file.status === 'done') {
        this.$message.success('上传成功!')
        this.imageList.push(data.file.response.data)
        this.previewVideoUrl = this.imageList
        console.log('video      ', this.imageList)
        this.sendDatas()
      }
      if (data.file.status === 'error') {
        this.$message.error('上传失败!')
      }
    },
    isVideoTime(data, time) {
      this.affixFileList = []
      return new Promise((resolve, reject) => {
        let url = URL.createObjectURL(data.file.originFileObj)
        console.log(url)
        let audioElement = new Audio(url)
        audioElement.addEventListener('loadedmetadata', function() {
          console.log(audioElement.duration)
          this.videoTime = audioElement.duration
          console.log(this.videoTime)
          if (this.videoTime < time) {
            resolve(true)
          } else {
            resolve(false)
          }
        })
      })
    },
    // 上传视频
    videoBeforeUpload(file) {
      this.affixFileList = []
      this.imageList = []
      console.log(file)
      return new Promise((resolve, reject) => {
        const isJpgOrPng = file.type === 'video/mp4'
        const isLt10M = file.size / 1024 / 1024 < 10
        if (!isJpgOrPng) {
          this.$message.error('只能上传mp4格式的视频!')
          // this.affixFileList = []
          return isJpgOrPng
          // return reject(false)
        } else if (!isLt10M) {
          // this.affixFileList = []
          this.$message.error('视频大小不能超过10M!')
          return isLt10M
          // return reject(false)
        } else {
          return resolve(true)
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.titleMess {
  font-size: 18px;
}
.ant-divider {
  margin: 15px 0;
}
.ant-form {
  .ant-select {
    width: 170px;
    margin-right: 10px;
  }
  .ant-input {
    width: 200px;
  }
  .ant-upload-list {
    width: 200px;
  }
}
.addBtn {
  margin-top: 20px;
}
.tishi {
  margin-left: 5px;
  font-size: 12px;
  color: #7f7f7f;
}
.add_btn,
.del_btn {
  padding: 0 10px;
  cursor: pointer;
  margin-left: 10px;
}
.getId {
  font-size: 12px;
  margin-left: 10px;
}
.ant-form-item {
  display: flex;
}
</style>
